//
//  MainTabBarController.swift
//  RacWeibo
//
//  Created by hanxu on 15/10/8.
//  Copyright © 2015年 hanxu. All rights reserved.
//

import UIKit
import ReactiveCocoa

class MainTabBarController: UITabBarController {

    override func loadView() {
        super.loadView()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        addChildViewControllers()
//        setupComposeBtn()
    }
    /// 视图将要出现，可能会被调用多次，例如：push 一个 vc，再 pop 回来，此方法会被再次调用
    /// 不适合做多次执行的代码
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        // 不能重复添加按钮，因此 addSubview 方法放在了懒加载内部
        setupComposeBtn()
    }
    
    func addChildViewControllers() {
        
        addChildViewController(HomeController(), title: "首页", image: "tabbar_home")
        addChildViewController(MessageController(), title: "消息", image: "tabbar_message_center")
        // add an empty controller -> put composeBtn HERE
        addChildViewController(UIViewController())
        addChildViewController(DiscoveryController(), title: "发现", image: "tabbar_discover")
        addChildViewController(ProfileController(), title: "我", image: "tabbar_profile")
    }
    private func addChildViewController(childController: UIViewController, title: String, image: String) {

        tabBar.tintColor = UIColor.orangeColor()
        let childController = BaseTableViewController()
        childController.title = title
        childController.tabBarItem.image = UIImage(named: image)
        childController.tabBarItem.selectedImage = UIImage(named: image + "_highlighted")
        let nav = UINavigationController(rootViewController: childController)
        addChildViewController(nav)
    }
    
    private func setupComposeBtn() {
        
        let count = childViewControllers.count
        let h = tabBar.frame.height
        let w = UIScreen.mainScreen().bounds.width / CGFloat(count)
        let rect = CGRectMake(0, 0, w, h)
        
        composeButton.frame = CGRectOffset(rect, 2 * w, 0)
    }
    
    lazy var composeButton : UIButton = {
        let btn = UIButton()
        
        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        btn.rac_signalForControlEvents(UIControlEvents.TouchUpInside).subscribeNext({ (_) -> Void in
            printLog("你好")
        })
        self.tabBar.addSubview(btn)
        
        return btn
    }()

}
